var express = require('express');
var router = express.Router();
let Query=require('../tools/db')
let {api_url}=require('../config/config')



//获取搜索课程列表数据
router.get('/searchList',async (req, res, next)=>{
  let {keyword='',page=1,pageSize=4}=req.query
  page=Number(page)
  pageSize=Number(pageSize)

  //keyword是必填项，不填则报错
  if(keyword==''){
    next('搜索框不能为空')
    return
  }

  let sql1=`SELECT * FROM e_course WHERE title LIKE '%${keyword}%'`
  let [,res1]=await Query(sql1)
  let totalNum=res1.length
  let totalPage=Math.ceil(totalNum/pageSize)
  let sql2=`SELECT id,cid,title,price,CONCAT('${api_url}','/upload/course/',image_src) AS image_src,type_name,area_name,subject_name FROM e_course WHERE title LIKE '%${keyword}%' ORDER BY id DESC LIMIT ${(page-1)*pageSize},${pageSize}`
  let [,res2]=await Query(sql2)
  res.send({
    code:200,
    msg: 'ok',
    result:{
      keyword,
      page,
      pageSize,
      totalNum,
      totalPage,
      date: res2
     }
  })

})

//获取课程cid获取详情信息
router.get('/detail',async (req, res, next)=>{
    let {cid=''}=req.query
  
    //cid是必填项，不填则报错
    if(cid==''){
      next('cid不能为空')
      return
    }
  
    let sql1=`SELECT * FROM e_course WHERE cid='${cid}'`
    let [,res1]=await Query(sql1)
    let tid=res1[0].tid
    let sql2=`SELECT * FROM e_teacher WHERE tid='${tid}'`
    let [,res2]=await Query(sql2)
    res2[0].head_photo_url=`${api_url}/upload/avatar/${res2[0].head_photo_url}`
    let sql3=`SELECT id,cid,video_title FROM e_video WHERE cid='${cid}'`
    let [,res3]=await Query(sql3)
    res.send({
      code:200,
      msg: 'ok',
      result:{
        course:res1[0],
        teacher:res2[0],
        videos:res3
       }
    })
  
  })


module.exports = router;